﻿using SmartHRMS.Model.Account;
using StructureMap;
using System.Collections.Generic;
using System;

namespace SmartHRMS.Presentation.Account
{
    public class UserListPresenter
    {
        private IUserListView view;
        private IUserService userService;

        public UserListPresenter(IUserListView view)
        : this(ObjectFactory.GetInstance<IUserService>(), view)
        {
        }

        public UserListPresenter(IUserService userService, IUserListView view)
        {
            this.view = view;
            this.userService = userService;
        }

        public void Display()
        {
            clearInfoAndErrorMessages();

            IList<User> allUsers;

            allUsers = userService.FindAll();

            this.view.User = allUsers;
        }

        public void Filter(int criteria, string value)
        {
            clearInfoAndErrorMessages();

            IList<User> filteredUsers;

            if (criteria == 0)//filtering by user name (character containing).
            {
                filteredUsers = new List<User>();
                filteredUsers = userService.FindUsersByName(value);
            }
            else//filtering by employee code (character containing).
            {
                filteredUsers = new List<User>();
                filteredUsers = userService.FindUsersByEmployeeCode(value);
            }

            this.view.FilteredUsers = filteredUsers;
        }

        public void RemoveUserBy(Guid userId)
        {
            clearInfoAndErrorMessages();

            User user;
            user = userService.FindBy(userId);

            if (user != null)
            {
                userService.Remove(user);
                Display();
            }
            else
            {
                // Update error view
                this.view.ErrorMessage(String.Format("A user with an Id of '{}' cannot be found", userId));
            }
        }

        private void clearInfoAndErrorMessages()
        {
            view.ErrorMessage(string.Empty);
            view.InfoMessage(string.Empty);
        }
    }
}
